package com.amap.navi;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.mgroup.wazehelper.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.Log;
import cn.sinjet.carassist.SinjetApplication;
import cn.sinjet.communication.bluetooth.BluetoothModel;
import cn.sinjet.entity.RouteLine;
import cn.sinjet.entity.ShortPOI;
import cn.sinjet.model.carassist.AppModel;
import cn.sinjet.model.carassist.CarAssistService;
import cn.sinjet.model.carassist.Settings;
import cn.sinjet.prototol.codec.ToureDevCodec;
import cn.sinjet.utils.SharedPreferenceUtil;
import cn.sinjet.viewmodel.PageDefine;
import cn.sinjet.viewmodel.ViewModel;

/*
 * @author: Sinjet Navigation Model 
 */
@SuppressLint("DefaultLocale")
@SuppressWarnings("deprecation")
public class NaviModel{
	public static NaviModel instance = null;
	private static String tag = "navi";
    private Context mContext = null;
    private boolean isRoutePlaned = false;
    private List<ShortPOI> lstHistoryPOI = null;
    private List<ShortPOI> lstMyFavorPOI = null;
	private List<RouteLine> lstRouteLine = null;
    private String curCityName = "";
    private String startPointName = "我的位置";
    private String endPointName = "";
    
    private ShortPOI mStartPointPOI = null;
    private ShortPOI mEndPointPOI = null;
    private double mCurPosLatitude = 0.0;
    private double mCurPosLongitude = 0.0;
    
    private ShortPOI mHomePoi = null;
	private ShortPOI mOfficePoi = null;
//	private PowerManager powerManager = null;
//	private WakeLock wakeLock = null;
	boolean mIsNavigating = false;
    
    public NaviModel(){
    }
    
    public void init(Context context) {
		// TODO Auto-generated method stub
    	this.mContext = context;
    	if(context == null){
    		Log.i(tag, "ERRRRRRRRRRRRRRRRRRRRRRR");
    		return;
    	}

//    	BaiduTTSModel.getInstance(context);
		restoreNaviUserData();
	}
    
    public static NaviModel getInstance(){
    	if(instance == null)
    		instance = new NaviModel();
       return instance;	
    }
    
    
    public ShortPOI getHomeAddress(){
    	return mHomePoi;
    }
    public ShortPOI getOfficeAddress(){
    	return mOfficePoi;
    }
   
    public Settings getSettings(){
    	return AppModel.getInstance().getSettings();
    }

    public void setCurrentPosition(double latitude,double longitude){
    	Log.i(tag, "set cur pos:"+latitude+" ,"+longitude);
    	mCurPosLatitude = latitude;
    	mCurPosLongitude = longitude;

        if(mStartPointPOI == null){//never set a start point or never located before
        	mStartPointPOI = new ShortPOI();
        	mStartPointPOI.title = "我的位置";
        	mStartPointPOI.latitude = latitude;
        	mStartPointPOI.longitude = longitude;
        	mStartPointPOI.isCurrentPosition = true;
        }else if(mStartPointPOI.isCurrentPosition){//update current position
        	mStartPointPOI.latitude = latitude;
        	mStartPointPOI.longitude = longitude;
        }
    	
    	if(null != mEndPointPOI && mEndPointPOI.isCurrentPosition){
              mEndPointPOI.latitude = latitude;
              mEndPointPOI.longitude = longitude;
    	}
    }
    
  
    public ShortPOI getStartPoint(){
    	if(mStartPointPOI.isCurrentPosition){
    		mStartPointPOI.latitude = mCurPosLatitude;
    		mStartPointPOI.longitude = mCurPosLongitude;
    	}
    	
    	return mStartPointPOI;
    }
  
    
    public ShortPOI getEndPoint(){
       return mEndPointPOI;
    }
    
    public void restoreNaviUserData(){
    	try{
	    	   SharedPreferenceUtil util = new SharedPreferenceUtil(mContext);
	    	   lstHistoryPOI = util.getHistoryPOIs();
	    	   mHomePoi = util.getHomeAddress();
	    	   mOfficePoi = util.getOfficeAddress();
	    	   curCityName = util.getCityName();
	    	   lstRouteLine = util.getLinesRecords();
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
    }
    
    public void storeNaviUserData(){
    	Log.i(tag, "storePOIData");
    	try{
	    	   SharedPreferenceUtil util = new SharedPreferenceUtil(mContext);
	    	   util.setHomeAddress(mHomePoi);
	    	   util.setOfficeAddress(mOfficePoi);
	    	   util.setHistoryPOIs(lstHistoryPOI);
	    	   util.setCityName(curCityName);
	    	   util.setLinesRecords(lstRouteLine);
	    	}catch(Exception e){
	    		e.printStackTrace();
	    }
    }
    
    
    public void addNewUsedPOI(ShortPOI poi){
    	if(poi == null) return;
    	Log.i("navi", "add new poi:"+poi.id);
    	if(lstHistoryPOI == null) lstHistoryPOI = new ArrayList<ShortPOI>();
    	for(ShortPOI eachPoi:lstHistoryPOI){
    		if(eachPoi.id.equals(poi.id)){
    			Log.i("navi", "poi id exited!");
    			return;
    		}
    	}
    	lstHistoryPOI.add(poi);
    }
    
    public void addNewLineRecord(RouteLine line){
    	if(line == null) return;
    	if(lstRouteLine == null) lstRouteLine = new ArrayList<RouteLine>();
    	
    	for(RouteLine eachline:lstRouteLine){
    		if(eachline.startPoint.isCurrentPosition && line.startPoint.isCurrentPosition){
    			 if(eachline.endPoint.id.equals(line.endPoint.id)) return;//start point is current position, end point is equal 
    		}
    		else if(eachline.startPoint.id.equals(line.startPoint.id)&&eachline.endPoint.id.equals(line.endPoint.id)){
    			return;
    		}
    	}
    	lstRouteLine.add(line);
    }
    
    
    public void addMyFavorPOI(ShortPOI poi){
    	if(poi == null)
    		return;
    	Log.i("navi", "add new myfavor poi:"+poi.id);
    	if(lstMyFavorPOI == null)
    		lstMyFavorPOI = new ArrayList<ShortPOI>();
    	for(ShortPOI eachPoi:lstMyFavorPOI){
    		if(eachPoi.id.equals(poi.id)){
    			Log.i("navi", "poi id exited!");
    			return;
    		}
    	}
    	lstMyFavorPOI.add(poi);
    }
    
    public List<ShortPOI> getUsedShortPOIs(){
    	return lstHistoryPOI;
    }
    
    public List<RouteLine> getRouteLines(){
    	return lstRouteLine;
    }
    
    public void deleteUsedPOI(ShortPOI item){
    	if(lstHistoryPOI.contains(item))
    		lstHistoryPOI.remove(item);
    }
    
    public void deleteAllUsedPOI(){
    	if(lstHistoryPOI != null)
    		lstHistoryPOI.clear();
    }
    public void deleteRouteLine(RouteLine line){
    	if(lstRouteLine.contains(line))
    		lstRouteLine.remove(line);
    }
    
    public void deleteAllLinesRecord() {
		// TODO Auto-generated method stub
	    if(lstRouteLine != null){
	    	lstRouteLine.clear();
	    }
	}
    
    public List<ShortPOI> getMyFavorPOIs(){
    	return lstMyFavorPOI;
    }
    
    public void deleteMyFavorItem(ShortPOI item){
    	if(lstMyFavorPOI.contains(item))
    		lstMyFavorPOI.remove(item);
    }
    
    
	public int getDayNightMode() {
		return getSettings().dayNightMode;
	}
	
	public int getDayOrNight(){
		  if(getSettings().dayNightMode == 0){//if it is autoMode
			    long time = System.currentTimeMillis();
			    final Calendar calendar = Calendar.getInstance();
			    calendar.setTimeInMillis(time);
			    int hour = calendar.get(Calendar.HOUR_OF_DAY);
//			    int minute = calendar.get(Calendar.MINUTE);
//			    Log.i("test","get time: "+hour+"h"+minute+"m");
			    if(hour >= 6 && hour < 18)
			    	return 1;
			    else 
			    	return 2;
		  }else{
		       return getSettings().dayNightMode;
		  }
	}

	public void setDayNightMode(int dayNightMode) {
		getSettings().dayNightMode = dayNightMode;
	}

	/*public int getHeadMode() {
		return headMode;
	}*/

/*	public void setHeadMode(int headMode) {
		this.headMode = headMode;
	}*/

	public boolean isTrafficVoiceOn() {
		return getSettings().isTrafficVoiceOn;
	}

	public void setTrafficVoiceOn(boolean isTrafficVoiceOn) {
		getSettings().isTrafficVoiceOn = isTrafficVoiceOn;
	}

	
	public boolean isKeepScreenOn() {
		return getSettings().isKeepScreenOn;
	}

	public void setKeepScreenOn(boolean isKeepScreenOn) {
		getSettings().isKeepScreenOn = isKeepScreenOn;
	}

	public String getCurCityName() {
		return curCityName;
	}

	public void setCurCityName(String curCityName) {
		this.curCityName = curCityName;
	}

	private int[] mRouteIds = null;
	private int mSelectedRouteIndex = 0;
	public int[] getRouteIds() {
		// TODO Auto-generated method stub
		return mRouteIds;
	}
	
	public void setRouteIds(int[] routeIds){
		this.mRouteIds = routeIds;
	}

	public int getSelectedRouteIndex() {
		return mSelectedRouteIndex;
	}

	public void setSelectedRouteIndex(int mSelectedRouteIndex) {
		this.mSelectedRouteIndex = mSelectedRouteIndex;
	}

	public String getEndPointName() {
		return endPointName;
	}

	public void setEndPointName(String endPointName) {
		this.endPointName = endPointName;
	}


		int mDspCamera = 0;
		void handleCamera(int dsp){
			Log.i(tag, "dsp camera:"+dsp);
			if(mDspCamera == dsp) return;
			mDspCamera = dsp;
			if(dsp == 1) ViewModel.getIns().setViewVisible(R.id.meter_camera, 1);
			else ViewModel.getIns().setViewVisible(R.id.meter_camera, 0);
		}
		int mLimitSpeed = 0;
		void handleLimitSpeed(int limitSpeed){
			Log.d(tag, "limit speed:"+limitSpeed);
			if(mLimitSpeed == limitSpeed) return;
			mLimitSpeed = limitSpeed;
			if(mLimitSpeed == 0) {
				ViewModel.getIns().setViewVisible(R.id.meter_limit_speed, 0);
			}else {
				String strLimitSpeed = String.valueOf(limitSpeed);
				ViewModel.getIns().setViewProperty(R.id.meter_limit_speed, strLimitSpeed);
				ViewModel.getIns().setViewVisible(R.id.meter_limit_speed, 1);
			}
		}
		
	
	int  mIsCameraDsp = 0; 
	boolean bShowCameraInfo = false;
	
	public void playText(String playText){
//		TTSController.getInstance(mContext).playText(playText);
//		BaiduTTSModel.getInstance(mContext).playText(playText);
	}
	
	int mOldSpeed = 0;
	protected void displaySpeed(float speed) {
		// TODO Auto-generated method stub
		Log.i("test", "get gps Speed:"+speed);
		if(BluetoothModel.getInstance().isConnected()) return;
		if(speed >=0.0f && speed <=240.0f){
			int speedDegree = (int)speed;
			if(mOldSpeed == speedDegree) return;
			mOldSpeed = speedDegree;
			ViewModel.getIns().setViewProperty(R.id.meter_speed_meter, speedDegree);
			ViewModel.getIns().setViewProperty(R.id.meter_speed_value, String.valueOf(speedDegree));
		}
	}
	
	int mOldWhich = -1;
	protected void displayBearing(float bearing) {
		 Log.i("test", "onGetBearing:"+bearing);
		// TODO Auto-generated method stub
		if (bearing < 0 || bearing > 360.0f)
		    return;
 
		float fWhich = (bearing / (360.0f / 16));
		int iWhich = (int)(fWhich+0.999f);
		iWhich = iWhich / 2;
		if(iWhich <0 || iWhich >7) iWhich = 0;
		
		if(mOldWhich == iWhich) return;
		mOldWhich = iWhich;
//		String[] strDirection = new String[]{"北","东北","东","东南","南","西南","西","西北"};
//        ViewModel.getIns().setViewProperty(R.id.meter_direction_value, strDirection[iWhich]);
	}
	

	public boolean isRoutePlaned() {
		return isRoutePlaned;
	}

	public void setRoutePlaned(boolean isRoutePlaned) {
		this.isRoutePlaned = isRoutePlaned;
	}
	public void deInit(){
        storeNaviUserData();		
	}
	
	ToureDevCodec toureCodec = new ToureDevCodec();
	
	public void onClkView(Context context,int tag){
		switch(tag){	
    	case R.id.simple_navi_set_back:
    		ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_SIMPLE_NAVI);
    		break;
    	case R.id.navi_set_route_detail:
    		ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_ROUTE_DETAIL);
    		break;
    	case R.id.navi_set_day_night_mode:
    		ViewModel.getIns().refreshView(R.id.navi_set_day_night_mode);
    		break;
    	case R.id.navi_set_traffic_voice:
    		setTrafficVoiceOn(!isTrafficVoiceOn());
    		ViewModel.getIns().setViewProperty(tag, (int)((isTrafficVoiceOn())?1:0));
    		break;
    	case R.id.navi_set_navi_voice:
    		AppModel.getInstance().getSettings().isNaviVoiceOn = !AppModel.getInstance().getSettings().isNaviVoiceOn;
    		int checked = (AppModel.getInstance().getSettings().isNaviVoiceOn)?1:0;
    		ViewModel.getIns().setViewProperty(tag,checked);
    		break;
		}
	}

	public boolean isHomeSet() {
		// TODO Auto-generated method stub
		if(mHomePoi == null) return false;
		else  return true;
	}

	
	/*public void goHome(Context context) {
		// TODO Auto-generated method stub
		setEndPoint(mHomePoi);
		requestCalculateRoute(context);
	}
*/
	public boolean isOfficeSet() {
		// TODO Auto-generated method stub
		if(mOfficePoi == null)   return false;
		else  return true;
	}

	/*public void gotoOffice(Context context) {
		// TODO Auto-generated method stub
		setEndPoint(mOfficePoi);
		requestCalculateRoute(context);
	}
*/
	public void setHomeAddress(ShortPOI shortPOI) {
		// TODO Auto-generated method stub
		mHomePoi = shortPOI;
	}

	public void setOfficeAdress(ShortPOI shortPOI) {
		// TODO Auto-generated method stub
		mOfficePoi = shortPOI;
	}

//		TimeCountDownUtil mCountDownTimer = null;
		private void startTimeCountDownForNavi(){
//		    if(mCountDownTimer != null)
//		    	mCountDownTimer.cancel();
//		    if(mCountDownTimer == null)
//			CountDownTimer mCountDownTimer = new TimeCountDownUtil(R.id.true_navi, 10000, 1000);
//	     	mCountDownTimer.start();
	   }
	  public void cancelTimeCountDown(){
//		if(mCountDownTimer != null)
//			mCountDownTimer.cancel();
	 }
	  
	 
	
	private void delayToStartLocation(){
		Handler msgHandler = SinjetApplication.getInstance().getMsgClient().getMsgHandler();
		if(msgHandler != null)
			msgHandler.sendEmptyMessageDelayed(CarAssistService.MSG_CHECK_NETWORK, 10000);
	}
	public void checkNetworkStartLocation(){
		if(isNetworkAvailable()){
			Log.i(tag, "isNetworkAvailable start location");
//			startLocation();
		}else{
			delayToStartLocation();
			Log.i(tag, "delayToStartLocation");
		}
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager mgr = (ConnectivityManager) mContext.getApplicationContext()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}
	void onClkStrategy(int viewId){
		switch(viewId){
		case R.id.navi_strategy_avoid_highspeed:
			getSettings().mAvoidHighSpeed = (getSettings().mAvoidHighSpeed==1)?0:1;
			if(getSettings().mAvoidHighSpeed == 1 && getSettings().mHighSpeed==1){
				getSettings().mHighSpeed = 0;
				ViewModel.getIns().setViewProperty(R.id.navi_strategy_highspeed, getSettings().mHighSpeed);
			}
			ViewModel.getIns().setViewProperty(R.id.navi_strategy_avoid_highspeed, getSettings().mAvoidHighSpeed);
			break;
		case R.id.navi_strategy_congestion:
			getSettings().mCongestion = (getSettings().mCongestion == 1)?0:1;
			ViewModel.getIns().setViewProperty(R.id.navi_strategy_congestion, getSettings().mCongestion);
			break;
		case R.id.navi_strategy_highspeed:
			getSettings().mHighSpeed = (getSettings().mHighSpeed==1)?0:1;
			if(getSettings().mHighSpeed==1 && getSettings().mAvoidHighSpeed == 1 ){
				getSettings().mAvoidHighSpeed = 0;
				ViewModel.getIns().setViewProperty(R.id.navi_strategy_avoid_highspeed, getSettings().mAvoidHighSpeed);
			}
			if(getSettings().mHighSpeed ==1 && getSettings().mCost == 1){
				getSettings().mCost = 0;
				ViewModel.getIns().setViewProperty(R.id.navi_strategy_cost, getSettings().mCost);
			}
			ViewModel.getIns().setViewProperty(R.id.navi_strategy_highspeed, getSettings().mHighSpeed);
			break;
		case R.id.navi_strategy_cost:
			getSettings().mCost = (getSettings().mCost == 1)?0:1;
            if(getSettings().mCost == 1 && getSettings().mHighSpeed == 1){
            	getSettings().mHighSpeed = 0;
            	ViewModel.getIns().setViewProperty(R.id.navi_strategy_highspeed,getSettings().mHighSpeed);
            }
            ViewModel.getIns().setViewProperty(R.id.navi_strategy_cost, getSettings().mCost);
			break;
		}
	}

	/*public void onClkSetHomeAddress() {
		// TODO Auto-generated method stub
		Context context = ViewModel.getIns().getCurContext();
//		TTSController.getInstance(context).playText("设置家的地址");
		playText("设置家的地址");
		 Intent naviIntent = new Intent(context,PoiSearchActivity.class);
		 naviIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
		 naviIntent.putExtra("requestCode", Utils.REQUEST_GO_HOME);
		 context.startActivity(naviIntent);
	}*/

	/*public void onClkSetOfficeAddress() {
		// TODO Auto-generated method stub
		Context context = ViewModel.getIns().getCurContext();
//		TTSController.getInstance(context).playText("设置公司地址");
		playText("设置公司地址");
		 Intent naviIntent = new Intent(context,PoiSearchActivity.class);
		 naviIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
		 naviIntent.putExtra("requestCode", Utils.REQUEST_TO_OFFICE);
		 context.startActivity(naviIntent);
	}*/

	
	/*public void onClkReturnTrip(Context context) {
		// TODO Auto-generated method stub
		exchangeStartAndEnd(context);
	}*/

	public boolean isAmapNavigating(){
		return mIsNavigating;
	}

	public void onNaviStop() {
		// TODO Auto-generated method stub
		mIsNavigating = false;
	}



	
	
}